package com.ittsang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.ittsang.dto.LoginFormDTO;
import com.ittsang.dto.R;
import com.ittsang.dto.UserDTO;
import com.ittsang.mapper.PostsMapper;
import com.ittsang.mapper.UserClubPostsMapper;
import com.ittsang.mapper.UserMapper;
import com.ittsang.pojo.User;
import com.ittsang.pojo.UserClubPosts;
import com.ittsang.service.UserService;
import com.ittsang.utils.RedisConstants;
import com.ittsang.utils.RegexUtils;
import com.ittsang.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.ittsang.utils.RedisConstants.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserClubPostsMapper userClubPostsMapper;

    @Resource
    private PostsMapper postsMapper;

    @Override
    public List<User> getUserList() {
        return userMapper.getUserList();
    }

    @Override
    public R sendCode(String phone, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return R.error("手机号格式错误！");
        }
        // 3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4.保存验证码到 redis       //set key value ex 120
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY +phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 5.发送验证码
        log.debug("发送短信验证码成功，验证码：{}",code);

        // 返回ok
        return R.ok();
    }

    @Override
    public R register(LoginFormDTO loginForm, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            // 2.如果不符合，返回错误信息
            return R.error("手机号格式错误！");
        }
        if (userMapper.isUser(loginForm.getPhone()) != null) {
            // 手机号被注册
            return R.error("手机号已被注册");
        }
        String password = DigestUtils.md5DigestAsHex(loginForm.getPassword().getBytes());
        userMapper.register(loginForm.getPhone(),loginForm.getPhone(), password);
        return R.ok("注册成功");
    }

    @Override
    public R passwordLogin(LoginFormDTO loginForm, HttpSession session) {
        if (userMapper.isUser(loginForm.getPhone()) == null) {
            // 手机号不对
            return R.error("账号或密码不对");
        }
        String password = userMapper.getUserPassword(loginForm.getPhone());
        if (!DigestUtils.md5DigestAsHex(loginForm.getPassword().getBytes()).equals(password)) {
            return R.error("账号或密码不对");
        }
        return getUser(loginForm);
    }

    @Override
    public R codeLogin(LoginFormDTO loginForm, HttpSession session) {
        if (userMapper.isUser(loginForm.getPhone()) == null) {
            // 手机号不对
            return R.error("无此账号");
        }
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        if (!Objects.equals(loginForm.getCode(), cacheCode)) {
            return R.error("验证码不正确");
        }

        return getUser(loginForm);
    }

    @Override
    public R getUserInfo() {

        UserDTO user = UserHolder.getUser();

        User user1 = userMapper.getUser(user.getTelephone());
        user1.setPassword("");
        return R.ok("获取成功").put("user", user1);
    }

    @Override
    public R alterUserInfo(User user) {
        UserDTO user1 = UserHolder.getUser();
        user.setId(Math.toIntExact(user1.getId()));
        int num = userMapper.alterUserInfo(user);
        if (num == 0) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R alterUserPhone(String phone, HttpServletRequest request) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            return R.error("手机号格式错误！");
        }
        if (userMapper.isUser(phone) != null) {
            // 手机号被注册
            return R.error("手机号已被注册");
        }
        UserDTO user = UserHolder.getUser();
        userMapper.alterUserPhone(user.getId() ,phone);
        deleteToken(request);
        UserHolder.removeUser();
        return R.ok("修改成功");
    }

    @Override
    public R alterUserPassword(String pwd, String npwd, HttpServletRequest request) {
        UserDTO user = UserHolder.getUser();
        String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        String password = userMapper.getUserPassword(user.getTelephone());
        if (!md5.equals(password)) {
            return R.error("原密码不正确");
        }
        String nmd5 = DigestUtils.md5DigestAsHex(npwd.getBytes());
        userMapper.alterUserPassword(user.getId(), nmd5);
        deleteToken(request);
        UserHolder.removeUser();
        return R.ok("修改成功");
    }

    @Override
    public R logout(HttpServletRequest request) {
        deleteToken(request);
        UserHolder.removeUser();
        return R.ok("退出登录成功");
    }

    @Override
    public R logoutClub() {
        UserDTO user = UserHolder.getUser();
        UserClubPosts userClubPosts = userClubPostsMapper.getUserRole(Math.toIntExact(user.getId()), user.getClubId());
        // 判断是否是会长
        if (userClubPosts.getPostsId() == 0) {
            // 判断社团是否还有会长
            List<UserClubPosts> userClubPosts1 = userClubPostsMapper.getAllUserRole(user.getClubId());
            if (userClubPosts1 == null) {
                return R.error("退出失败，需要将会长职位传递给他人，方能退出");
            }
        }
        boolean i = userMapper.logoutClub(user.getId());
        return i ? R.ok("退出成功") : R.error("退出失败");
    }

    private R getUser(LoginFormDTO loginForm) {
        User user = userMapper.getUser(loginForm.getPhone());
//        UserDTO userDTO1 = BeanUtil.fillBeanWithMap((Map<?, ?>) user, new UserDTO(), false);
//        UserHolder.saveUser(userDTO1);
        String token = UUID.randomUUID().toString(true);
        System.out.println(token);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));

        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        Map<Object, Object> userMap1 = stringRedisTemplate.opsForHash()
                .entries(tokenKey);
        System.out.println(userMap1);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);
        return R.ok("登录成功").put("token", token);
    }

    private void deleteToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        String key = RedisConstants.LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().delete(key, "id", "telephone", "roleId", "clubId");
    }


    @Override
    public R managerLogin(LoginFormDTO loginForm) {
        if (userMapper.isUser(loginForm.getPhone()) == null) {
            // 手机号不对
            return R.error("账号或密码不对");
        }
        String password = userMapper.getUserPassword(loginForm.getPhone());
        if (!DigestUtils.md5DigestAsHex(loginForm.getPassword().getBytes()).equals(password)) {
            return R.error("账号或密码不对");
        }
        User user = userMapper.getUser(loginForm.getPhone());
        if (user.getRoleId()== 0) {
            return R.error("无权限");
        }
        return getUser(loginForm);
    }

    @Override
    public R getUserById(Integer userId) {
        User user = userMapper.getUserById(userId);
        UserClubPosts userRole = userClubPostsMapper.getUserRole(user.getId(), user.getClubId());
        // 判断是否有职位
        if (user.getDepartmentId() == 0) {
            user.setDepartment("会长");
        }
        if (userRole != null) {
            user.setRole(1);
            user.setDepartment(postsMapper.getPostNameById(userRole.getPostsId()));
        }
        return R.ok("获取成功").put("user", user);
    }
}
